package com.ebeitech.camera;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.OrientationEventListener;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.ebeitech.doorapp.util.PublicUtil;
import com.ebeitech.doorapp.view.BaseActivity;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.util.SPManager;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.doorapp.R;

import java.io.File;

public class QPIPicturePreviewActivity extends BaseActivity {

	public static final int RESULT_NEXT = 0X119;
	public static final int RESULT_RECAPURE = 0X11A;
	private String picPath = null;
	private HandWrite handWrite = null;
	public static final String FILE_PATH_SEPARATOR = ";";
	private static final int IMAGE_QUALITY = 80;
	public static final String TAG = "QPIPicturePreviewActivity";
	private boolean saveresult = false;
	
	private ImageView start;
	private ImageView clear;
	private ImageView delete;
	private View use;
	private TextView useCount;
	
	private boolean mCurrentOrient = false;
	private boolean mScreenProtrait = true;
	private int mLastRotation;
	private String mRepairOrderCode;
	private String mLocationName;
	private OrientationEventListener mOrientationEventListener;
	
	private View.OnClickListener mOnClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			//清楚涂鸦
			case R.id.ivDelete:
				onClearClick(v);
				break;
			case R.id.view_use:
				start.setEnabled(false);
				use.setEnabled(false);
				onBtnConfirmClicked(v);
				break;
			//重拍
			case R.id.exit:
				onBtnRecaptureClicked(v);
				break;
			//再拍一张
			case R.id.start:
				start.setEnabled(false);
				use.setEnabled(false);
				onBtnNextClicked(v);
				break;
			default:
				break;
			}
		}
	};

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.ebei.building.inspection.ui.BaseFlingActivity#onCreate(android.os
	 * .Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		if (savedInstanceState == null) {
			savedInstanceState = new Bundle();
		}
		savedInstanceState.putBoolean(SPConstants.IS_FIT_STATUS_BAR, false);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ebei_activity_media_picture_preview);
		setupViews();
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
	private void setupViews() {
		// TODO Auto-generated method stub
		Intent intent = getIntent();
		if (intent != null) {
			picPath = intent
					.getStringExtra(QPICameraFragment.BITMAP_PATH_EXTRA);
			mRepairOrderCode = intent.getStringExtra("repairOrderCode");
			mLocationName = intent.getStringExtra("locationName");
			if (!StringUtil.isStringNullOrEmpty(picPath)) {
				handWrite = (HandWrite) findViewById(R.id.handwrite);
				handWrite.setBitmapPath(picPath);
				handWrite.setOnModifyListener(new HandWrite.OnModifyListener() {
					
					@Override
					public void onModify() {
						// TODO Auto-generated method stub
						Log.i(TAG, "setOnModifyListener : onModify()");
						clear.setVisibility(View.VISIBLE);
					}

					@Override
					public void onClear() {
						// TODO Auto-generated method stub
						Log.i(TAG, "setOnModifyListener : onClear()");
						clear.setVisibility(View.INVISIBLE);
					}

				});
				//TextView tv = (TextView) findViewById(R.id.tvTitle);
				//tv.setText(R.string.picture_preview);

				//Button btnRight = (Button) findViewById(R.id.btnRight);
				//btnRight.setVisibility(View.GONE);
				
				start = (ImageView) findViewById(R.id.start);
				clear = (ImageView) findViewById(R.id.ivDelete);
				delete = (ImageView) findViewById(R.id.exit);
				use = findViewById(R.id.view_use);
				useCount = (TextView) findViewById(R.id.use_count);
				
				start.setEnabled(true);
				use.setEnabled(true);
				start.setImageResource(R.drawable.ebei_camera_recapture_selector);
				clear.setImageResource(R.drawable.ebei_camera_clear_selector);
				delete.setImageResource(R.drawable.ebei_camera_delete_selector);
				View useImage = findViewById(R.id.use);
				useImage.measure(0, 0);
				RelativeLayout.LayoutParams lp = (LayoutParams) use.getLayoutParams();
				lp.width = useImage.getMeasuredWidth();
				lp.height = useImage.getMeasuredHeight();
				use.setLayoutParams(lp);
				clear.setVisibility(View.INVISIBLE);
				use.setVisibility(View.VISIBLE);
				useCount.setVisibility(View.VISIBLE);
				findViewById(R.id.ivSetting).setVisibility(View.GONE);
				findViewById(R.id.ivFlashSetting).setVisibility(View.GONE);
				start.setOnClickListener(mOnClickListener);
				clear.setOnClickListener(mOnClickListener);
				use.setOnClickListener(mOnClickListener);
				delete.setOnClickListener(mOnClickListener);
				
				mOrientationEventListener = new MyOrientationEventListener(this);
				mOrientationEventListener.enable();
				
				useCount.setText(getPictureCount() + "");
				return;
			}
		}
		setResult(RESULT_CANCELED);
		finish();
	}

	public void onBtnBackClicked(View v) {
		done(RESULT_CANCELED);
	}

	public void onBtnConfirmClicked(View v) {
		done(RESULT_OK);
	}
	
	public void onBtnNextClicked(View v) {
		done(RESULT_NEXT);
	}

	public void onBtnRecaptureClicked(View v) {
		done(RESULT_RECAPURE);
	}

	public void onBtnCancelClicked(View v) {
		done(RESULT_CANCELED);
	}

	public void onClearClick(View v) {
		handWrite.clear();
		clear.setVisibility(View.INVISIBLE);
	}

	private void done(int resultCode) {

		if (RESULT_OK == resultCode || RESULT_NEXT == resultCode) {
			picPath = handWrite.saveBitmap();

			if (StringUtil.isStringNullOrEmpty(picPath)) {
				return;
			}
			String filePaths = SPManager.getInstance(this).get(SPConstants.PHOTOS_KEY, "");
			if (!StringUtil.isStringNullOrEmpty(filePaths)) {
				filePaths = filePaths + FILE_PATH_SEPARATOR + picPath;
			} else {
				filePaths = picPath;
			}
			SPManager.getInstance(this).put(SPConstants.PHOTOS_KEY, filePaths);
		} else {
			File f = new File(picPath);
			if (f.exists()) {
				try {
					f.delete();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}

		Intent intent = new Intent();
		intent.putExtra(QPICameraFragment.BITMAP_PATH_EXTRA, picPath);

		setResult(resultCode, intent);
		finish();
	}
	
	
	private int getPictureCount() {
		int count = 1;
		String filePaths = SPManager.getInstance(this).get(SPConstants.PHOTOS_KEY, "");
		if (!StringUtil.isStringNullOrEmpty(filePaths)) {
			if (filePaths
					.contains(QPIPicturePreviewActivity.FILE_PATH_SEPARATOR)) {
				String[] paths = filePaths
						.split(QPIPicturePreviewActivity.FILE_PATH_SEPARATOR);
				count = paths.length + 1;
			} else {
				count = 2;
			}
		}
		return count;
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (mOrientationEventListener != null) {
			mOrientationEventListener.disable();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		// 屏蔽回退键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	@SuppressLint("NewApi")
	class MyOrientationEventListener extends OrientationEventListener {

		public MyOrientationEventListener(Context context) {
			super(context);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onOrientationChanged(int rotation) {
			// TODO Auto-generated method stub
			if (((rotation >= 0) && (rotation <= 45)) || (rotation >= 315)||((rotation>=135)&&(rotation<=225))) {//portrait
				// protrait
				mCurrentOrient = true;
				if (mCurrentOrient != mScreenProtrait) {
					mScreenProtrait = mCurrentOrient;
					Log.i(TAG ,"竖屏");
					int widgetRotation = 0;
					PublicUtil.setRotation(start, widgetRotation);
					PublicUtil.setRotation(clear, widgetRotation);
					PublicUtil.setRotation(delete, widgetRotation);
					PublicUtil.setRotation(use, widgetRotation);
					//useCount.setRotation(widgetRotation);
					mLastRotation = rotation;
				}
			} else if (((rotation > 45) && (rotation < 135))
					|| ((rotation > 225) && (rotation < 315))) {
				// landscape
				mCurrentOrient = false;
				if (Math.abs(mLastRotation - rotation) > 90 || mCurrentOrient != mScreenProtrait) {
					mScreenProtrait = mCurrentOrient;
					Log.i(TAG ,"横屏");
					int widgetRotation = 0;
					if(rotation < 135) {
						widgetRotation = 270;
					} else {
						widgetRotation = 90;
					}
					PublicUtil.setRotation(start, widgetRotation);
					PublicUtil.setRotation(clear, widgetRotation);
					PublicUtil.setRotation(delete, widgetRotation);
					PublicUtil.setRotation(use, widgetRotation);
					//useCount.setRotation(widgetRotation);
					mLastRotation = rotation;
				}
			}
		}
	};
	
}
